package com.nintendo.frame;

import com.nintendo.entity.pojo.Desk;
import com.nintendo.frame.edit.UpdateDeskFrame;
import com.nintendo.mapper.DeskDao;
import com.nintendo.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class DeskFrame extends JFrame {

    private JTextField nameField;
    private JTextField seatsField;
    private JComboBox<String> statusComboBox;
    private JButton addButton;
    private JButton deleteButton;
    private JButton saveButton;
    private JButton updateButton; // 新增更新按钮
    private JTable table;
    private DefaultTableModel model;

    public DeskFrame() {

        setTitle("餐台管理");
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        // 创建面板
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new GridLayout(4, 2, 10, 10));

        // 名称标签和文本框
        JLabel nameLabel = new JLabel("名称:");
        nameField = new JTextField();
        inputPanel.add(nameLabel);
        inputPanel.add(nameField);

        // 座位数标签和文本框
        JLabel seatsLabel = new JLabel("座位数:");
        seatsField = new JTextField();
        inputPanel.add(seatsLabel);
        inputPanel.add(seatsField);

        // 状态标签和组合框
        JLabel statusLabel = new JLabel("状态:");
        String[] statuses = {"可用", "不可用", "维护中"};
        statusComboBox = new JComboBox<>(statuses);
        inputPanel.add(statusLabel);
        inputPanel.add(statusComboBox);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        addButton = new JButton("添加");
        deleteButton = new JButton("删除");
        saveButton = new JButton("保存");
        updateButton = new JButton("更新"); // 新增更新按钮

        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(saveButton);
        buttonPanel.add(updateButton); // 添加更新按钮到面板

        // 添加动作监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addDesk();
            }
        });

        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteDesk();
            }
        });

        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveDesk();
            }
        });

        updateButton.addActionListener(new ActionListener() { // 更新按钮动作监听器
            @Override
            public void actionPerformed(ActionEvent e) {
                updateDesk();
            }
        });

        // 创建表格模型
        model = new DefaultTableModel();
        model.addColumn("名称");
        model.addColumn("座位数");
        model.addColumn("状态");

        // 创建表格
        table = new JTable(model);

        // 设置内容面板
        getContentPane().add(inputPanel, BorderLayout.NORTH);
        getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);

        // 加载数据库中的数据
        loadDataFromDatabase();
    }

    public void loadDataFromDatabase() {
        try (SqlSession session = MyBatisUtils.getSqlSession()) {
            DeskDao mapper = session.getMapper(DeskDao.class);
            List<Desk> desks = mapper.selectAll();
            for (Desk desk : desks) {
                model.addRow(new Object[]{desk.getNo(), desk.getSeating(), desk.getStatus()});
            }
        }
    }

    private void addDesk() {
        String name = nameField.getText();
        String seatsStr = seatsField.getText();
        String status = (String) statusComboBox.getSelectedItem();

        if (!name.isEmpty() && !seatsStr.isEmpty()) {
            int seats = Integer.parseInt(seatsStr);
            Desk desk = new Desk();
            desk.setNo(name);
            desk.setSeating(Integer.valueOf(seatsStr));
            desk.setStatus(status);
            try (SqlSession session = MyBatisUtils.getSqlSession()) {
                DeskDao mapper = session.getMapper(DeskDao.class);
                mapper.insert(desk);
                session.commit();
            }

            model.addRow(new Object[]{name, seats, status});
            clearFields();
        } else {
            JOptionPane.showMessageDialog(this, "请填写完整信息");
        }
    }

    private void deleteDesk() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow != -1) {
            String name = (String) model.getValueAt(selectedRow, 0);
            try (SqlSession session = MyBatisUtils.getSqlSession()) {
                DeskDao mapper = session.getMapper(DeskDao.class);
                mapper.deleteByName(name); // 假设有一个根据名称删除的方法
                session.commit();
            }
            model.removeRow(selectedRow);
        } else {
            JOptionPane.showMessageDialog(this, "请选择要删除的餐台");
        }
    }

    private void saveDesk() {
        // 保存餐台逻辑
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < model.getRowCount(); i++) {
            sb.append("餐台 ").append(i + 1).append(": ");
            sb.append("名称: ").append(model.getValueAt(i, 0)).append(", ");
            sb.append("座位数: ").append(model.getValueAt(i, 1)).append(", ");
            sb.append("状态: ").append(model.getValueAt(i, 2)).append("\n");
        }
        JOptionPane.showMessageDialog(this, sb.toString());
    }

    private void clearFields() {
        nameField.setText("");
        seatsField.setText("");
        statusComboBox.setSelectedIndex(0);
    }

    private void updateDesk() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow != -1) {
            String name = (String) model.getValueAt(selectedRow, 0);
            try (SqlSession session = MyBatisUtils.getSqlSession()) {
                DeskDao mapper = session.getMapper(DeskDao.class);

                Desk desk = mapper.selectByName(name); // 假设有一个根据名称查询的方法
                UpdateDeskFrame.showUpdateDeskFrame(desk, this);
            }
        } else {
            JOptionPane.showMessageDialog(this, "请选择要更新的餐台");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new DeskFrame().setVisible(true);
            }
        });
    }
}
